package com.nbgs.demo.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbgs.demo.common.Alipay;
import com.nbgs.demo.common.Info.OrderForm;
import com.nbgs.demo.common.Result;
import com.nbgs.demo.common.Uitls;
import com.nbgs.demo.config.AlipayConfig;
import com.nbgs.demo.controller.info.*;
import com.nbgs.demo.model.Complain;
import com.nbgs.demo.model.PaymentRecords;
import com.nbgs.demo.service.UserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@Slf4j
@Api(tags = "用户相关接口", description = "提供用户相关的 Rest API")
@CrossOrigin("*")
@SessionAttributes(value = "cardNum")
public class UserController {
    @Autowired
    private UserService userService;
    private static String CARDNUM;
    /**
     * 通过水卡卡号找到账单
     * @return
     */
    @GetMapping("/find")
    public Result findWaterBillByCardId(HttpSession httpSession){
        log.info("执行通过水卡id找到为缴费和逾期的账单");
        Object cardNum = httpSession.getAttribute("cardNum");
        System.out.println("我得到的cardNum1111"+cardNum);
        this.CARDNUM= (String) cardNum;
        //找到没有交费的账单,这里需要一个水卡卡号
        String num= (String) cardNum;
        //通过这个水卡卡号去获得对应的id
        int cardId = userService.findCardIdByCardNum(num);
        System.out.println("通过卡号获得的水卡id为："+cardId);
        List<BillConsumptionInfo> unfinished = userService.findWaterBillByCardNum(cardId,"未缴","逾期");
        if(unfinished==null){
            //返回的success为false
            return Result.success("暂无欠费信息");
        }
        //总欠费
        double money=0;
        for(BillConsumptionInfo bc:unfinished){
            money=money+bc.getPayable()+bc.getOverdue();
            System.out.println("账单为："+bc);
        }
        System.out.println("总共欠费"+money);
        //创建一个对象，将欠费信息与信息放进去，传给前端
        WaterBillInfo waterBillInfo=new WaterBillInfo();
        waterBillInfo.setMoney(money);
        waterBillInfo.setAllBill(unfinished);
        return Result.success(waterBillInfo);
    }


    /**
     * 用户缴费之后，此方法将账单中未缴和逾期的状态改为已缴，并生成对应的缴费记录表 和 发票表
     * @return
     */
    @PostMapping("/pay")
    public Result payForBill(HttpSession session, double money){
        log.info("这里执行缴费之后将未缴和逾期的账单状态改为已缴");
        Object cardNum = session.getAttribute("cardNum");
        System.out.println("我得到的cardNum1111"+cardNum);
        String num= (String) cardNum;
        //找到没有交费的账单,这里需要一个水卡卡号
        //通过这个水卡卡号去获得对应的id
        int cardId = userService.findCardIdByCardNum(num);
        System.out.println("通过卡号获得的水卡id为："+cardId);
        List<BillConsumptionInfo> unfinished = userService.findWaterBillByCardNum(cardId,"未缴","逾期");
        //这里将所有账单id拼接为唯一的一个支付宝订单编号
        String moneyInfo=money+"";
        int a= (int) (Math.random()*100);
        String orderNum="WNGS"+a;
        for(BillConsumptionInfo info:unfinished){
            String billId=info.getBillId()+"";
            orderNum=orderNum+billId;
        }
        OrderForm orderForm=new OrderForm("水费",orderNum,moneyInfo);
        System.out.println("支付开始");
        Result alipay = Alipay.getAlipay(orderForm);
        System.out.println("支付结束,返回："+alipay);
        System.out.println(alipay.isSuccess());
//        for(BillConsumptionInfo bc:unfinished){
//            int billId = bc.getBillId();
//            userService.updateByBillId(billId);
//            System.out.println("我修改了id为:"+billId+"的账单状态");
//            PaymentRecords pr=new PaymentRecords();
//            pr.setCardId(cardId);
//            //这里算出每个账单缴费的金额
//            double yj=bc.getPayable()+bc.getOverdue();
//            pr.setPayMoney(yj);
//            //添加当前时间
//            pr.setPaymentDate(Uitls.getTime());
//            //并获得当前账单的年月
//            String month = bc.getConsumptionMonth();
//            pr.setConsumptionMonth(month);
//            //获得用水量
//            double ys=bc.getConsumptionVolume();
//            pr.setConsumptionVolume(ys);
//            userService.addPaymentRecords(pr);
//            System.out.println("我已完成了缴费记录表的增加");
//        }
        return alipay;
    }



    /**
     *  带查询年份的 分页查询--查询该水卡的所有用水信息
     * @param currPage
     * @param Size
     * @param year
     * @return
     */
    @GetMapping("/findWaterMessage")
    public Result findWaterMessageByCardId(HttpSession session, @RequestParam(defaultValue = "1")int currPage, @RequestParam(defaultValue = "5")int Size, String year){
        log.info("通过水卡id找到全部的用水信息,参数为:{},{},{}"+currPage,Size,year);
        System.out.println("currPage"+currPage);
        System.out.println("Size"+Size);
        System.out.println("年份信息"+year);
        Object cardNum = session.getAttribute("cardNum");
        String num= (String) cardNum;
        //通过这个水卡卡号去获得对应的id
        int cardId = userService.findCardIdByCardNum(num);
        System.out.println("通过卡号获得的水卡id为："+cardId);

        Page<ConsumptionInfo> pageParm = new Page<>();
        pageParm.setCurrent(currPage);
        pageParm.setSize(Size);
        IPage<ConsumptionInfo> infoIPage = userService.findWaterMessageByCardId(pageParm,year,cardId);

        List<ConsumptionInfo> records = infoIPage.getRecords();
        for(ConsumptionInfo cinfo:records){
            cinfo.setConsumptionVolume(cinfo.getConsumptionEnd()-cinfo.getConsumptionStart());
            System.out.println("查出来的信息:"+cinfo);
        }
        return Result.success(infoIPage);
    }

    /**
     * 查询缴费信息
     * @param currPage
     * @param pageSize
     * @return
     */
    @GetMapping("/findPaymentRecords")
    public Result findPaymentRecordsByCardId(HttpSession session,@RequestParam(defaultValue = "1")int currPage, @RequestParam(defaultValue = "5")int pageSize){
        log.info("通过水卡id找到全部的缴费信息,参数为:{},{}"+currPage,pageSize);
        Object cardNum = session.getAttribute("cardNum");
        String num= (String) cardNum;
        //通过这个水卡卡号去获得对应的id
        int cardId = userService.findCardIdByCardNum(num);
        System.out.println("通过卡号获得的水卡id为："+cardId);

        Page<PaymentRecords> pageParm = new Page<>();
        pageParm.setCurrent(currPage);
        pageParm.setSize(pageSize);
        IPage<PaymentRecords> infoIPage = userService.findPaymentRecordsByCardId(pageParm,cardId);
        List<PaymentRecords> records = infoIPage.getRecords();
        for(PaymentRecords pr:records){

            System.out.println("查出来的缴费信息为:"+pr);
        }
        return Result.success(infoIPage);
    }

    /**
     * 用户投诉之后，添加到投诉表
     * @param complainInfo
     * @return
     */
    @PostMapping("/addComplain")
    public Result addComplain(HttpSession session,ComplainInfo complainInfo){
        log.info("执行增加投诉的操作，参数为{}",complainInfo);
        Object cardNum = session.getAttribute("cardNum");
//        找到没有交费的账单,这里需要一个水卡卡号
        String num= (String) cardNum;
//        通过这个水卡卡号去获得对应的id
        int cardId = userService.findCardIdByCardNum(num);
        System.out.println("通过卡号获得的水卡id为："+cardId);

        Complain complain = new Complain();
        complain.setCardId(cardId);
        complain.setComplainStartData(Uitls.getTime());
        complain.setComplainMessage(complainInfo.getComplainMessage());
        complain.setComplainTel(complainInfo.getComplainTel());
        complain.setComplainType(complainInfo.getComplainType());
        complain.setComplainState("未处理");
        userService.addComplain(complain);

        return Result.success();
    }

    /**
     * 用户查询自己的投诉
     * @return
     */
    @GetMapping("/findComplain")
    public Result findComplain(HttpSession session){
        log.info("执行查找投诉的操作");
        Object cardNum = session.getAttribute("cardNum");
//        找到没有交费的账单,这里需要一个水卡卡号
        String num= (String) cardNum;
//        通过这个水卡卡号去获得对应的id
        int cardId = userService.findCardIdByCardNum(num);
        System.out.println("通过卡号获得的水卡id为："+cardId);

        List<Complain> complains = userService.findComplainByCardId(cardId);
        for(Complain c:complains){
            System.out.println(c);
        }
        return Result.success();
    }

//    @GetMapping("/payBool")
//    public void payBool(){
//        System.out.println("后台收到了支付成功的请求");
//    }

    /**
     //     * 支付宝服务器异步通知
     //     *
     //     * @param request
     //     * @throws Exception
     //     */
    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request,HttpSession session) throws Exception {
        System.out.println("我跳转到了");
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type); // 调用SDK验证签名

        if (signVerified) { // 验证成功 更新订单信息
            System.out.println("异步通知成功");
            // 商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            // 交易状态
            String trade_status = request.getParameter("trade_status");
            // 修改数据库
            log.info("这里执行缴费成功之后将未缴和逾期的账单状态改为已缴");
//            Object cardNum = session.getAttribute("cardNum");
//            //找到没有交费的账单,这里需要一个水卡卡号
            String num= this.CARDNUM;
//            //通过这个水卡卡号去获得对应的id
            int cardId = userService.findCardIdByCardNum(num);
            System.out.println("通过卡号获得的水卡id为："+cardId);
            List<BillConsumptionInfo> unfinished = userService.findWaterBillByCardNum(cardId,"未缴","逾期");
            for(BillConsumptionInfo bc:unfinished){
                int billId = bc.getBillId();
                userService.updateByBillId(billId);
                System.out.println("我修改了id为:"+billId+"的账单状态");
                PaymentRecords pr=new PaymentRecords();
                pr.setCardId(cardId);
                //这里算出每个账单缴费的金额
                double yj=bc.getPayable()+bc.getOverdue();
                pr.setPayMoney(yj);
                //添加当前时间
                pr.setPaymentDate(Uitls.getTime());
                //并获得当前账单的年月
                String month = bc.getConsumptionMonth();
                pr.setConsumptionMonth(month);
                //获得用水量
                double ys=bc.getConsumptionVolume();
                pr.setConsumptionVolume(ys);
                userService.addPaymentRecords(pr);
                System.out.println("我已完成了缴费记录表的增加");
            }
        } else {
            System.out.println("异步通知失败");
        }
    }

}